package com.book.service.impl;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.book.dao.OrderDao;
import com.book.entity.BookEntity;
import com.book.entity.CartEntity;
import com.book.entity.OrderEntity;
import com.book.entity.OrderItemEntity;
import com.book.exception.GlobalException;
import com.book.feign.CartFeign;
import com.book.service.OrderItemService;
import com.book.service.OrderService;
import com.book.utils.PageUtils;
import com.book.utils.Query;
import com.book.utils.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.javafx.collections.MappingChange;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Resource
    private CartFeign cartFeign;

    @Resource
    private OrderDao orderDao;

    @Resource
    private OrderItemService orderItemService;





    public String createOrder(Long userId){
        R cart = cartFeign.getCart(userId);
        if(cart == null){
            throw new GlobalException(500,"当前商品为空，下单失败！！");
        }
        Map map = (Map) cart.get("cart");
        String books = (String) cart.get("bookJson");
        OrderEntity order = new OrderEntity();
        String orderId = System.currentTimeMillis() + "" + userId;
        order.setUserId(userId);
        order.setOrderId(orderId);
        order.setTotalCount((Integer) map.get("totalCount"));
        order.setTotalAmount(new BigDecimal(Double.valueOf( map.get("totalPrice")==null? "0" :map.get("totalPrice").toString())));
        ObjectMapper mapper = new ObjectMapper();
        List<BookEntity> bookEntities = null;
        try {
            bookEntities = mapper.readValue(books, List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        List<OrderItemEntity> orderItems = new ArrayList<>();
        bookEntities = mapper.convertValue(bookEntities, new TypeReference<List<BookEntity>>() {
        });
        bookEntities.forEach(book ->{
            book.setSales(book.getSales() + book.getCount());
            book.setStock(book.getStock() - book.getCount());
            if(book.getStock() < 0){
                throw new GlobalException(500,book.getName() + "库存不足！！");
            }
            book.setUpdatetime(null);
            book.setCreatetime(null);
            System.out.println("~~~~~~~~book:  " + book);
            cartFeign.update(book);
            orderItems.add(new OrderItemEntity(null, book.getId(), userId, orderId, book.getName(),book.getPrice(),book.getCount(),book.getTotalPrice(),null));

        });
        order.setOrderItemEntities(orderItems);
        order.setStatus(1);
        this.save(order);
        orderItemService.saveBatch(orderItems);
        cartFeign.clearCart(userId);
        return orderId;
    }

    @Override
    public List<OrderEntity> getOrderById(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        return orderDao.selectList(queryWrapper);
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

}